package com.guigu.dh.service.impl;

import com.guigu.dh.common.result.Result;
import com.guigu.dh.pojo.hosp.Department;
import com.guigu.dh.repository.DepartmentRepository;
import com.guigu.dh.service.DepartmentService;
import com.guigu.dh.vo.hosp.DepartmentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    // 根据医院编号查询科室，并按格式封装好
    @Override
    public Result queryDepartmentByHoscode(String hoscode) {
        // 封装条件
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        // 查出数据
        List<Department> all = departmentRepository.findAll(example);
        // 使用stream流中的集合分组方法，根据大科室编号分组
        Map<String, List<Department>> listMap =
                all.stream().collect(Collectors.groupingBy(Department::getBigcode));
        // 创建需要返回的集合，用于封装集合数据
        List<DepartmentVO> list = new ArrayList<>();

        for (Map.Entry<String, List<Department>> stringListEntry : listMap.entrySet()) {
            // 封装大科室数据
            String key = stringListEntry.getKey();
            List<Department> value = stringListEntry.getValue();
            // 创建封装大科室对象
            DepartmentVO departmentVO = new DepartmentVO();
            departmentVO.setDepcode(key);
            departmentVO.setDepname(value.get(0).getBigname());

            // 创建集合用来装小科室数据
            List<DepartmentVO> departmentVOList = new ArrayList<>();
            // 封装小科室数据
            for (Department department : value) {
                DepartmentVO departmentVO1 = new DepartmentVO();
                departmentVO1.setDepcode(department.getDepcode());
                departmentVO1.setDepname(department.getDepname());

                // 加入大科室对象中集合中
                departmentVOList.add(departmentVO1);
            }
            // 将结合存入对象中
            departmentVO.setChildren(departmentVOList);

            // 将对象存入集合中
            list.add(departmentVO);
        }
        return Result.ok(list);
    }
}
